import React, { FC, useEffect, useState } from "react";
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import { DateType } from "../type";

dayjs.extend(customParseFormat);

interface DateInputProps {
  value: DateType | null;
  onChange: (value: DateType | null) => void;
  placeholder?: string;
}

const DateInput: FC<DateInputProps> = (props) => {
  const { value, onChange, placeholder } = props;
  const YYMMDD = value ? value?.format("YYYY-MM-DD") : "";
  const HHmmss = value ? value?.format("HH:mm:ss") : "";
  const [date, setDate] = useState<string>(YYMMDD);
  const handleChange = (v?: string) => {
    setDate(v || "");
    if (v) {
      if (dayjs(v, "YYYY-MM-DD", true).isValid()) {
        let nextDate = `${v} 00:00:00`;
        if (HHmmss) {
          nextDate = `${v} ${HHmmss}`;
        }
        onChange(dayjs(nextDate));
      }
    }
  };
  useEffect(() => {
    if (YYMMDD && YYMMDD !== date) {
      setDate(YYMMDD);
    }
  }, [value, YYMMDD]);
  return (
    <input
      type="text"
      placeholder={placeholder}
      value={date}
      onChange={(e) => handleChange(e.target.value)}
    />
  );
};

export default DateInput;
